import os, json, requests, time, pymysql
from pprint import pprint
from tests.ry_roll_up_banner.common import constant
from tests.ry_roll_up_banner.common.util_common import *
from tests.ry_roll_up_banner.common.custom_data import *

now = time.strftime("%Y%m%d-%H%M")  # 当前的时间
print("当前时间" + now)
host_url = constant.host_url

# 因为每次运行都要创建一个商场就很麻烦了，就指定一个商场
mallId = constant.mallId
mallName = constant.mallName
cityId = constant.cityId  # 上海
floorId = constant.floorId
mall_groupId = constant.mall_groupId  # 该商场的素材分组
layoutId_custom = constant.layoutId_custom  # 建站的配置id
appcode_custom = constant.appcode_custom
userId = constant.userId  # 商家后台的账号id
ryoms_userId = constant.ryoms_userId  # 大运营后台的账号id


cus_dir = str(os.path.dirname(os.path.dirname(__file__)))
cus_dir = cus_dir.replace('\\', '/')
print(cus_dir)


def mall_add_custom():
    print("为该商场配置建站   " + str(mallId))
    header = {
        "Cookie": dayunying_login(),
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 "
                      "Safari/537.36"}
    url = host_url + "/easy-smart-basic/module/setmodulebylayout"
    data = {"layoutId": layoutId_custom, "mallId": mallId, "moduleIds": "701"}  # 701建站的id
    r = requests.post(url, headers=header, json=data)
    print(r.status_code, r.json())
    result = r.json()
    assert result['meta']['msg'] == "success"

    url_peizhi = host_url + "/easy-smart-web/layoutFunction/functionRightSave"
    data_peizhi = {"mallId": mallId, "layoutId": layoutId_custom,
                   "layoutFunctionList": [{"functionId": 1, "functionName": "模板", "status": 1, "checked": True},
                                          {"functionId": 2, "functionName": "精彩活动", "status": 1,
                                           "checked": True},
                                          {"functionId": 3, "functionName": "公共设施", "status": 1,
                                           "checked": True},
                                          {"functionId": 4, "functionName": "商品分类", "status": 1,
                                           "checked": True},
                                          {"functionId": 5, "functionName": "商品推荐", "status": 1,
                                           "checked": True}]}
    r_peizhi = requests.post(url_peizhi, headers=header, json=data_peizhi)
    print(r_peizhi.status_code, r_peizhi.json())
    result_1 = r_peizhi.json()
    assert result_1['meta']['msg'] == "success"


def add_ryoms_custom_case():
    print("添加大运营的建站模板")
    url = host_url + "/mcp-gateway/template/save?"
    header = {
        "Cookie": dayunying_login(),
        "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
    }
    casename = "auto" + str(time.strftime("%H%M%S"))
    print(casename)
    config1 = json.dumps(ryoms_custom_data_one)  # json转成字符串
    data = {"adsFlag": 0,
            "config": config1,
            "coverImgUrl": "",
            "templateType": "MALL",
            "composeType": "PORTRAIT",
            "name": casename,
            "bannerAds": 0,
            "userId": ryoms_userId
            }

    r = requests.post(url=url, headers=header, data=data)
    print(r.json())
    assert r.json()['meta']['msg'] == "操作成功"
    template_id = r.json()["result"]["data"]  # 添加模板，返回该模板的id
    print(template_id)
    print("添加大运营的建站模板-->      成功")
    return template_id


def deploy_ryoms_custom_case(templateId):  # templateId=443
    print("发布大运营的建站模板")
    url = host_url + "/mcp-gateway/template/deploy"
    header = {
        "Cookie": dayunying_login(),
        "Content-Type": 'application/x-www-form-urlencoded;charset=UTF-8',
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
    }
    data = {"userId": 1, "templateId": templateId, "releaseType": 1}
    print("发布大运营的")
    r = requests.post(url=url, headers=header, data=data)
    print(r.json())
    assert r.json()['meta']['msg'] == "操作成功"
    print("发布大运营的建站模板-->      成功")


def custom_case_setting_detail():
    print("获取建站商场配置的模板数据详情")
    url = host_url + "/easy-smart-web/templateConfigure/layoutDetail"
    header = {
        "Cookie": dayunying_login(),
        "Content-Type": 'application/json',
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
    }
    data = {"mallId": mallId}
    r = requests.post(url=url, headers=header, json=data)
    case_detail = r.json()["result"]["data"]
    print(case_detail)
    print("获取建站商场配置的模板数据详情  ---->   成功")
    return case_detail


def custom_case_setting_save(templateId):
    print("建站商场配置的模板数据详情保存，给与模板数据权限，模板id是    ------>  " + str(templateId))
    url = host_url + "/easy-smart-web/templateConfigure/layoutTemplateSave"
    header = {
        "Cookie": dayunying_login(),
        "Content-Type": 'application/json',
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
    }
    case_detail = custom_case_setting_detail()
    for i in case_detail:
        if i["templateId"] == templateId:
            i['status'] = 1
            print("修改对应模板的发布状态权限为1， 模板id是    ------>   " + str(templateId))
    data = {"mallId": mallId, "data": case_detail}
    r = requests.post(url=url, headers=header, json=data)
    print(r.json())
    assert r.json()['meta']['msg'] == "success"
    print("建站商场配置的模板数据详情保存，给与模板数据权限  ---->   成功")


def add_shop_custom_case(templateId):
    print("添加商家后台的建站作品")
    # URL在线编码解码工具（UrlEncode编码和UrlDecode解码）
    url = host_url + "/mcp-gateway/case/save"
    header = {
        "Cookie": shop_login(),
        "Content-Type": 'application/x-www-form-urlencoded;charset=UTF-8',
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
    }
    shop_casename = "auto" + str(time.strftime("%H%M%S"))
    config1 = json.dumps(custom_shop_data_one)  # json转成字符串
    data = {
        "config": config1,
        "coverImgUrl": "",
        "caseType": "MALL",
        "composeType": "PORTRAIT",
        "name": shop_casename,
        "templateId": templateId,
        "templateThemeId": 0,
        "mallId": mallId,
        "userId": userId
    }
    r = requests.post(url=url, headers=header, data=data)
    print(r.json())
    assert r.json()['meta']['msg'] == "操作成功"
    case_id = r.json()["result"]["data"]
    print("添加商家后台的建站作品-->      成功, 返回作作品id为 ---->   " + str(case_id))
    return case_id


def delete_all_custom_template(name="auto"):
    print("删除大运营的所有建站模板")
    url = host_url + "/mcp-gateway/template/list?userId=1&templateType=&composeType=&adsFlag=&releaseFlag=&name=" + name + "&pageNo=1&pageSize=30&phase=DEV"
    header = {
        "Cookie": dayunying_login(),
        "Content-Type": 'application/json',
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
    }
    data = {}
    r = requests.get(url=url, headers=header, json=data)
    assert r.json()['meta']['msg'] == "操作成功"
    template_list = r.json()['result']['data']['list']
    for case in template_list:
        caseId = case['id']
        # print(caseId)
        delete_custom_ryoms_template(str(caseId))
    print("删除大运营的所有建站模板 ---->    ok")


def delete_custom_ryoms_template(templateId):
    print("删除大运营的建站模板, 模板是  ---->    " + str(templateId))
    url = host_url + "/mcp-gateway/template/delete"
    header = {
        "Cookie": dayunying_login(),
        "Content-Type": 'application/x-www-form-urlencoded',
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
    }
    data = {"userId": userId, "templateId": templateId}
    r = requests.post(url=url, headers=header, data=data)
    assert r.json()['meta']['msg'] == "操作成功"
    print("删除大运营的建站模板  ---->    ok")


def delete_custom_shop_case(caseId):
    print("删除商家的建站模板, 作品case是  ---->    " + str(caseId))
    url = host_url + "/mcp-gateway/case/delete"
    header = {
        "Cookie": shop_login(),
        "Content-Type": 'application/x-www-form-urlencoded',
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
    }
    data = {"userId": userId, "caseId": caseId}
    r = requests.post(url=url, headers=header, data=data)
    assert r.json()['meta']['msg'] == "操作成功"
    print("删除商家的建站模板  ---->    ok")


def delete_all_custom_shop_case():
    print("删除商家的所有建站模板")
    url = host_url + "/mcp-gateway/case/list?userId=" + str(
        userId) + "&name=&caseType=&composeType=&pageNo=1&pageSize=8"
    header = {
        "Cookie": shop_login(),
        "Content-Type": 'application/json',
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
    }
    data = {}
    r = requests.get(url=url, headers=header, json=data)
    print(r.json())
    caseId_list = r.json()['result']['data']['list']
    for case in caseId_list:
        caseId = case['id']
        delete_custom_shop_case(str(caseId))
    print("删除商家的所有建站模板 ---->    ok")


def getMallAppCaseList_custom():
    print("商家后台应用中心-获取应用模板caseid  商场id是  " + str(mallId))
    url = host_url + '/easy-smart-basic/mallApplication/getMallAppCaseList'
    header = {
        "Cookie": shop_login(),
        "Content-Type": 'application/json',
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
    }

    data = {"appCode": appcode_custom, "mallId": mallId, "auditState": 2, "pageSize": 1000}
    r = requests.post(url=url, headers=header, json=data)
    print(r.json())
    # caseId = r.json()['result']['data']
    caseId_custom = []
    caseId_list = r.json()['result']['data']# [0]['id']
    for case in caseId_list:
        caseId = case['id']
        caseId_custom.append(caseId)
        print(caseId)
    case_last = caseId_custom[-1]
    print("最新的建站作品id是  ---->  " + str(case_last))
    return str(case_last)


def upload_custom_video(videoname="test.mp4"):
    print("上传视频  " + str(videoname))
    video_path = cus_dir + "/data/" + videoname  # D:/pydj/ry_roll_up_banner
    url = host_url + "/easy-smart-web/fileUpload/uploadFile"
    # /easy-smart-web/merchantSource/saveMerchantSource 添加到大运营资源池
    header = {
        "Cookie": dayunying_login(),
    }
    # 遇到文件和参数都有的，那就文件传files   参数传data
    video = {'file': (videoname, open(video_path, 'rb'), 'video/mp4')}
    print(video)
    r = requests.post(url=url, headers=header, files=video)
    print(r.json())
    assert r.json()['meta']['msg'] == "success"
    return r.json()['result']['data']


def add_ryoms_custom_case_full():
    print("添加大运营的建站模板")
    url = host_url + "/mcp-gateway/template/save?"
    header = {
        "Cookie": dayunying_login(),
        "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
    }
    casename = "auto" + str(time.strftime("%H%M%S"))
    print(casename)
    config1 = json.dumps(ryoms_custom_data)  # 拿到，建站参数，json转成字符串
    data = {"adsFlag": 0,
            "config": config1,
            "coverImgUrl": "",
            "templateType": "MALL",
            "composeType": "PORTRAIT",
            "name": casename,
            "bannerAds": 0,
            "userId": ryoms_userId
            }

    r = requests.post(url=url, headers=header, data=data)
    print(r.json())
    assert r.json()['meta']['msg'] == "操作成功"
    template_id = r.json()["result"]["data"]  # 添加模板，返回该模板的id
    print(template_id)
    print("添加大运营的建站模板-->      成功")
    return template_id


def add_shop_custom_case_full(templateId):
    print("添加商家后台的建站作品")
    # URL在线编码解码工具（UrlEncode编码和UrlDecode解码）
    url = host_url + "/mcp-gateway/case/save"
    header = {
        "Cookie": shop_login(),
        "Content-Type": 'application/x-www-form-urlencoded;charset=UTF-8',
        "User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36"
    }
    shop_casename = "auto" + str(time.strftime("%H%M%S"))
    # config = open("custom_shop_config.txt").read()
    config1 = json.dumps(custom_shop_data)  # 拿到建站商家后台的参数，json转成字符串
    data = {
        "config": config1,
        "coverImgUrl": "",
        "caseType": "MALL",
        "composeType": "PORTRAIT",
        "name": shop_casename,
        "templateId": templateId,
        "templateThemeId": 0,
        "mallId": mallId,
        "userId": userId
    }
    r = requests.post(url=url, headers=header, data=data)
    print(r.json())
    assert r.json()['meta']['msg'] == "操作成功"
    case_id = r.json()["result"]["data"]
    print("添加商家后台的建站作品-->      成功, 返回作作品id为 ---->   " + str(case_id))
    return case_id

# mall_add_custom()
# add_ryoms_custom_case()
# deploy_ryoms_custom_case(templateId=443)
# custom_case_setting_detail()
# custom_case_setting_save(templateId=443)
# add_shop_custom_case(templateId=443)
# delete_custom_shop_case(caseId)
# delete_all_custom_shop_case()
# delete_custom_ryoms_template()
# getMallAppCaseList_custom()

# add_ryoms_custom_case_full()
# upload_custom_video(videoname="test.mp4")
# upload_custom_video_png(videoname="test.mp4")
# add_shop_custom_case_full(templateId=499)
delete_all_custom_template(name="auto")